/*
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-06-01 12:13:31
 * @LastEditors: voanit
 * @LastEditTime: 2022-06-07 16:30:00
 */
/* 类型申明文件 */
import { LoginForm, ApiResponse, Token } from '@/types/data'
import { RootThunkAction, LoginAction as LoginAction2 } from '@/types/store'
import request from '@/utils/request'

import { setToken, removeToken } from '@/utils/storage'

export const loginAction = (values: LoginForm): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.post<ApiResponse<Token>>('/authorizations', values)
    // console.log(res, 88);
    // 持久化
    setToken(res.data.data)

    /* 将token存在redux */
    dispatch({
      type: 'login/token',
      payload: res.data.data
    })
  }
}

export const getCode = (mobile: string): RootThunkAction => {
  return async (dispatch) => {
    await request.get(`/sms/codes/${mobile}`)
    // dispatch({
    //   type: '1',
    //   payload: ''
    // })
  }

}

export const logout = (): LoginAction2 => {
  removeToken()
  return {
    type: 'login/logout'
  }
}

export function saveToken(token: Token): LoginAction2 {
  // 1. 本地持久化
  setToken(token)

  // 2. 保存token
  return {
    type: 'login/token',
    payload: token
  }
}
